package com.wg.neptune.netty.client;

import com.wg.neptune.model.ProviderService;
import com.wg.neptune.model.RpcRequest;
import com.wg.neptune.netty.test.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * Created by mc on 18/5/29.
 * netty客户端
 */
public class NettyClient {

    private static EventLoopGroup group = new NioEventLoopGroup();
    private static Bootstrap b = new Bootstrap();
    private static Channel ch;



    public static void star(InetSocketAddress socketAddress ,RpcRequest rpcRequest) throws IOException{
        try {
        System.out.println("客户端成功启动...");
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyClientFilter());
        // 连接服务端
        ch = b.connect(socketAddress.getHostName(), socketAddress.getPort()).sync().channel();
        ch.writeAndFlush(rpcRequest);
        System.out.println("客户端发送数据:"+rpcRequest.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Netty创建全部都是实现自AbstractBootstrap。
     * 客户端的是Bootstrap，服务端的则是    ServerBootstrap。
     **/
    public static void main(String[] args) throws InterruptedException, IOException {
        String str="Hello Netty";
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",6789);
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setInvokeTimeout(1000);
        rpcRequest.setAppName("rpc");
        rpcRequest.setInvokedMethodName("say");
        ProviderService providerService = new ProviderService();
        providerService.setServiceItf(HelloService.class);
        providerService.setWorkThreads(10);
        //providerService.setServiceMethod();
        rpcRequest.setProviderService(providerService);

        star(socketAddress,rpcRequest);
    }

}